package com.webapp.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.webapp.domain.entity.Dict;
import com.webapp.domain.entity.DisputesData;
import com.webapp.domain.entity.User;

@Repository("userDAO")
public class UserDAO extends AbstractDAO<User>{

	public void inserUser(User user){
		save(user);
	}
	
	public User selectUser(Map<String, Object> map){
		List<Object> list = new ArrayList<Object>();
		String sql = "where 1=1 ";
		for(String key : map.keySet()){
			if ("name".equals(key)) {
				sql += "and ("+key+"=? or user.userDetail.phone=?) ";
				list.add(map.get(key));
				list.add(map.get(key));
			}else{
				sql += "and "+key+"=? ";
				list.add(map.get(key));
			}
		}
		return get(sql, list.toArray());
	}
	
	public void updateUser(User user){
		//Session session = getSession();
		//session.beginTransaction();
		getSession().merge(user);
		//session.getTransaction().commit();
		//session.close();
	}
	
	public User getUserByDisputesId(long disputesId){
		String sql = "SELECT u.* FROM USER u LEFT JOIN DISPUTES d ON u.ID=d.USER_ID WHERE d.ID=?";
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setParameter(0, disputesId);
		query.addEntity("u", User.class);
		User user = (User) query.uniqueResult();
		return user;
	}
	public User getUserBySessionId(long sessionId){
		String sql = "SELECT u.* FROM USER u LEFT JOIN DISPUTES d ON u.ID = d.USER_ID " +
				"LEFT JOIN SESSION s ON d.ID = s.DISPUTES_ID " +
				"WHERE s.ID = ?";
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setParameter(0, sessionId);
		query.addEntity("u", User.class);
		User user = (User) query.uniqueResult();
		return user;
	}
	
	/**
	 * 修改用户头像
	 * @param newImg
	 * @param userId
	 */
	public void updateHeadPortrait(final String newImg,final long id,final String sql){
		
		final SQLQuery query = getSession().createSQLQuery(sql);
		query.setString(0, newImg);
		query.setLong(1, id);
		query.executeUpdate();
		
	}
	/**
	 * test
	 * @return 
	 */
	@SuppressWarnings("unchecked")
	public int testUser(String test){
		String hql="update DisputesData b set title=:test where b.id=1";
		Query query=getSession().createQuery(hql);	
		query.setString("test", test);
		return query.executeUpdate();
	}
}
